﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace TestCS
{
    [StructLayout(LayoutKind.Sequential)]
    public class Person
    {
        public int age;
        public double salary;
    }
    public class PersonWrapper
    {
        [DllImport(@"E:\2021\study\18_pinvoketest\x64\Release\PVTest.dll")]
        internal static extern IntPtr CreateNewPerson();
        private IntPtr objPtr=IntPtr.Zero;
        public PersonWrapper()
        {
            this.objPtr = CreateNewPerson();
        }

        [DllImport(@"E:\2021\study\18_pinvoketest\x64\Release\PVTest.dll")]
        internal static extern void DeletePerson(IntPtr Ptr);

        [DllImport(@"E:\2021\study\18_pinvoketest\x64\Release\PVTest.dll")]
        internal static extern void SetPersonage(IntPtr Ptr,int age);

        [DllImport(@"E:\2021\study\18_pinvoketest\x64\Release\PVTest.dll")]
        internal static extern int GetPersonage(IntPtr Ptr);

        public void Dispose()
        {
            DeletePerson(this.objPtr);
            this.objPtr = IntPtr.Zero;
        }
        public int Age
        {
            set
            {
                SetPersonage(this.objPtr, value);
            }
            get
            {
                return GetPersonage(this.objPtr);
            }
        }
        ~PersonWrapper()
        {
            //DeletePerson(this.objPtr);
            if (this.objPtr != IntPtr.Zero)
            {
                Dispose();
            }
        }
    }
    internal class Program
    {
        [DllImport(@"E:\2021\study\18_pinvoketest\x64\Release\PVTest.dll")]
        internal static extern int AddInt(int a,int b);

        [DllImport(@"E:\2021\study\18_pinvoketest\x64\Release\PVTest.dll")]
        internal static extern void PrintString([MarshalAs(UnmanagedType.LPWStr)]string str);

        [DllImport(@"E:\2021\study\18_pinvoketest\x64\Release\PVTest.dll")]
        internal static extern void PassPerson(Person person);
        static void Main(string[] args)
        {
            int c= AddInt(10, 20);
            Console.WriteLine($"这个是C#的结果{c}");
            PrintString("打印C#中的字符串");

            Person person = new Person();
            person.age = 20;
            person.salary = 30;
            PassPerson(person);
            Console.WriteLine($"C#的Person:{person.age}");


            PersonWrapper person2 = new PersonWrapper();
            person2.Age = 300;
            Console.WriteLine(person2.Age);

            person2.Dispose();
            Console.Read();
        }

    }
}
